package com.exam.sacrifice.widget;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.exam.commonbiz.util.ScreenUtil;
import com.exam.sacrifice.R;

public class CustomPopupWindow {
    private Context context;
    private PopupWindow popupWindow;
    private View contentView;

    public CustomPopupWindow(Context context, int layoutResId) {
        this.context = context;
        initPopupWindow(layoutResId);
    }

    private void initPopupWindow(int layoutResId) {
        // 初始化内容视图
        contentView = LayoutInflater.from(context).inflate(layoutResId, null);
        // 创建PopupWindow
        popupWindow = new PopupWindow(
                contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        // 设置背景（必须设置，否则点击外部无法关闭）
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        // 设置点击外部可关闭
        popupWindow.setOutsideTouchable(true);

        // 设置动画
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
    }

    public void showAsDropDown(View view){
        // 显示PopupWindow在按钮的正上方
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1] - popupWindow.getHeight(); // 减去popup的高度使其显示在上方

        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, x, y);
    }

    /**
     * 在指定View的下方显示PopupWindow
     */
    public void showBelow(View anchor) {
        if (popupWindow != null && !popupWindow.isShowing()) {
            popupWindow.showAsDropDown(anchor);
        }
    }

    /**
     * 在指定View的上方显示PopupWindow
     */
    public void showAbove(View anchor) {
        if (popupWindow != null && !popupWindow.isShowing()) {
            // 计算位置
            int[] location = new int[2];
            anchor.getLocationOnScreen(location);

            int x = popupWindow.getWidth();
            int y = popupWindow.getHeight();

            popupWindow.showAtLocation(
                    anchor,
                    Gravity.NO_GRAVITY,
                    location[0],
                    location[1] - ScreenUtil.dp2px(context, 200));
        }
    }

    /**
     * 在指定View的左侧显示PopupWindow
     */
    public void showToLeft(View anchor) {
        if (popupWindow != null && !popupWindow.isShowing()) {
            // 计算位置
            int[] location = new int[2];
            anchor.getLocationOnScreen(location);

            popupWindow.showAtLocation(
                    anchor,
                    Gravity.NO_GRAVITY,
                    location[0] - popupWindow.getWidth(),
                    location[1]
            );
        }
    }

    /**
     * 在指定View的右侧显示PopupWindow
     */
    public void showToRight(View anchor) {
        if (popupWindow != null && !popupWindow.isShowing()) {
            popupWindow.showAsDropDown(anchor, anchor.getWidth(), 0);
        }
    }

    /**
     * 在指定View的中心显示PopupWindow
     */
    public void showAtCenter(View anchor) {
        if (popupWindow != null && !popupWindow.isShowing()) {
            popupWindow.showAtLocation(
                    anchor,
                    Gravity.CENTER,
                    0,
                    0
            );
        }
    }

    /**
     * 智能显示在View旁边（自动选择最佳位置）
     */
    public void showSmart(View anchor) {
        if (popupWindow == null || popupWindow.isShowing()) {
            return;
        }

        // 测量PopupWindow的宽高
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();
        int popupHeight = contentView.getMeasuredHeight();

        // 获取View的位置
        int[] location = new int[2];
        anchor.getLocationOnScreen(location);
        int viewX = location[0];
        int viewY = location[1];
        int viewWidth = anchor.getWidth();
        int viewHeight = anchor.getHeight();

        // 获取屏幕尺寸
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int screenWidth = metrics.widthPixels;
        int screenHeight = metrics.heightPixels;

        // 计算最佳显示位置
        if (viewY + viewHeight + popupHeight <= screenHeight) {
            // 下方有足够空间
            popupWindow.showAsDropDown(anchor);
        } else if (viewY - popupHeight >= 0) {
            // 上方有足够空间
            popupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, viewX, viewY - popupHeight);
        } else if (viewX + viewWidth + popupWidth <= screenWidth) {
            // 右侧有足够空间
            popupWindow.showAsDropDown(anchor, viewWidth, -viewHeight);
        } else if (viewX - popupWidth >= 0) {
            // 左侧有足够空间
            popupWindow.showAsDropDown(anchor, -popupWidth, -viewHeight);
        } else {
            // 默认显示在下方
            popupWindow.showAsDropDown(anchor);
        }
    }

    /**
     * 关闭PopupWindow
     */
    public void dismiss() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    /**
     * 获取PopupWindow的内容视图
     */
    public View getContentView() {
        return contentView;
    }
}
